package com.uiotsoft.small.sampler;

import org.apache.jmeter.config.Arguments;
import org.apache.jmeter.protocol.java.sampler.AbstractJavaSamplerClient;
import org.apache.jmeter.protocol.java.sampler.JavaSamplerContext;
import org.apache.jmeter.samplers.SampleResult;
import org.apache.jmeter.threads.JMeterContextService;
import org.apache.jmeter.threads.JMeterVariables;

public class HttpConnectSampler extends AbstractJavaSamplerClient {
    ComHttpClient httpClient;
    public Arguments getDefaultParameters() {
        Arguments params = new Arguments();
        params.addArgument("type", "app/host");
        params.addArgument("gateway", "${gateway}");
        params.addArgument("appKey", "${appKey}");
        params.addArgument("appSecret", "${appSecret}");
        return params;
    }

    @Override
    public SampleResult runTest(JavaSamplerContext javaSamplerContext) {
        JMeterVariables vars = JMeterContextService.getContext().getVariables();
        SampleResult results = new SampleResult();
        String type = javaSamplerContext.getParameter("type");
        String appKey = javaSamplerContext.getParameter("appKey");
        String appSecret = javaSamplerContext.getParameter("appSecret");
        String gateway = javaSamplerContext.getParameter("gateway");
        results.sampleStart();
        httpClient = new ComHttpClient(appKey, appSecret, gateway);
        if (type.toLowerCase().startsWith("app")){
            vars.putObject("appHttpClient", httpClient);
        }else if (type.toLowerCase().startsWith("host")){
            vars.putObject("hostHttpClient", httpClient);
        }
        if (httpClient != null){
            results.setSuccessful(true);
            results.setResponseData("Successful", "UTF-8");
            results.setResponseMessage("Http client created.");
            results.setResponseCodeOK();
        }else {
            results.setSuccessful(false);
            results.setResponseData("Create failed", "UTF-8");
            results.setResponseMessage("Failed to Create.");
            results.setResponseCode("501");
        }
        results.sampleEnd();
        return results;
    }
}
